import * as THREE from 'three'
import Base3D from '../index'
import { PerspectiveCamera } from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

export default class Camera {
  constructor() {
    this.base3D = Base3D.getInstance()
    this.canvas = this.base3D.canvas
    this.init()
  }
  init() {
    console.error('init  Camera========>')
    this.instance = new PerspectiveCamera(40, this.base3D.size.width / this.base3D.size.height, 0.6, 5200)
    this.instance.enabled = true
    this.instance.rotation.order = 'XYZ'
    this.base3D.scene.add(this.instance)
    this.cameraHelper
    this.createOrbitControls()
  }

  createOrbitControls() {
    console.error('init  OrbitControls========>')
    this.control = new OrbitControls(this.instance, this.canvas)
    this.control.enableDamping = true
    // 动态阻尼系数 就是鼠标拖拽旋转灵敏度
    this.control.dampingFactor = 0.04
    // 是否可以旋转
    this.control.enableRotate = true
    // 是否可以缩放与速度
    this.control.enableZoom = true
    // this.control.minZoom = 0.5
    // this.control.maxZoom = 2
    // 设置相机距离原点的最远距离
    this.control.minDistance = 1
    // 设置相机距离原点的最远距离
    this.control.maxDistance = 20000
    // 是否开启右键拖拽
    this.control.enablePan = true
    // this.control.maxPolarAngle = Math.PI / 3
    // this.control.minPolarAngle = -Math.PI / 3
  }

  createCameraHelper() {
    this.cameraHelper = new THREE.CameraHelper(this.instance)
    this.base3D.scene.add(this.cameraHelper)
  }

  removeCameraHelper() {
    this.cameraHelper && this.base3D.destoryObject(this.cameraHelper, this.base3D.scene)
    this.cameraHelper = null
  }

  resize() {
    this.instance.aspect = this.base3D.size.width / this.base3D.size.height
    this.instance.updateProjectionMatrix()
  }

  update() {
    if (this.instance && this.instance.enabled) {
      this.control.update()
    }
  }
}
